app.controller('UpKeepingCtrl', function($rootScope, $ionicConfig,$animateCss, $ionicPopup, $scope, $state, $stateParams, $timeout, $interval, BthSevice, FetchDataService, radialIndicatorInstance,$http,$myconfig, SPAService) {
     //获取当前登录用户信息
    $scope.userMes = JSON.parse(localStorage.getItem('user'));

    //定义保养时间记时默认时间
    $scope.HYBsec = 0;
    //获取当前系统时间
    if (!$rootScope.start) { //如果是未保养那就用最新时间
        SPAService.upKeepData.ThisTime = new Date();
    }

    //定义保养模式默认名
    var mode;
    //定义设备名
    var deviceName = '焕颜宝';

    // 定义默认保养状态
    // var maintain_sta = 0;



    var type = SPAService.upKeepData.type = $stateParams.type;
    $scope.valuesArr = [];
    $scope.typeTime = SPAService.upKeepData.typeTime = $rootScope.Yzb_time; //记录一份原始时间

    $scope.Count = 0;
    //开始保养
    function doIt(){
    switch (type){
        case 'jubu': // 抗皱美白
        mode = '局部光压';
            $rootScope.mode = '局部光压';
            $scope.valuesArr = kangzhou;
                // kangzhou
                // [0x7e, 0x04, 0x04, 0x01, 0xff, 0xff, 0xff, 0x00, 0xef],
                // [0x7e, 0x04, 0x01, 0x40, 0xff, 0xff, 0xff, 0x00, 0xef], // 设置亮度
                // [0x7e, 0x07, 0x05, 0x03, 0xe6, 0x00, 0x4d, 0x00, 0xef], // 设置颜色强度
                // [0x7e, 0x05, 0x03, 0x87, 0x03, 0xff, 0xff, 0x00, 0xef]  // 设置模式
            // ];
            $scope.title = '局部光压';
            $scope.typeSrc = 'img/icons/kangzhou.svg';
            typeTime = $rootScope.Yzb_time;
            break;
        case 'runfu': //
            mode = '润肤嫩肤';
            $rootScope.mode = '润肤嫩肤';
            $scope.valuesArr = quban;
                // quban
                // [0x7e, 0x04, 0x04, 0x01, 0xff, 0xff, 0xff, 0x00, 0xef],
                // [0x7e, 0x04, 0x01, 0x40, 0xff, 0xff, 0xff, 0x00, 0xef],
                // [0x7e, 0x07, 0x05, 0x03, 0x4d, 0x00, 0xcc, 0x00, 0xef],
                // [0x7e, 0x05, 0x03, 0x88, 0x03, 0xff, 0xff, 0x00, 0xef]
            // ];
            $scope.title = '润肤嫩肤';
            $scope.typeSrc = 'img/icons/runfu.svg';

            typeTime = $rootScope.Yzb_time;
            break;
        case 'quban':
            mode = '祛斑祛痘';
            $rootScope.mode = '祛斑祛痘';
            $scope.valuesArr = runfu;
                // runfu
                // [0x7e, 0x04, 0x04, 0x01, 0xff, 0xff, 0xff, 0x00, 0xef],
                // [0x7e, 0x04, 0x01, 0x40, 0xff, 0xff, 0xff, 0x00, 0xef],
                // [0x7e, 0x07, 0x05, 0x03, 0x99, 0x00, 0x4d, 0x00, 0xef],
                // [0x7e, 0x05, 0x03, 0x89, 0x03, 0xff, 0xff, 0x00, 0xef]
            // ];
            $scope.title = '祛斑祛痘';
            $scope.typeSrc = 'img/icons/qunban.svg';
            typeTime = $rootScope.Yzb_time;
            break;
        default: // 面膜导入
            mode = '面膜导入';
            $rootScope.mode = '面膜导入';
            $scope.valuesArr = daomo;
                // daomo
                // [0x7e, 0x04, 0x04, 0x01, 0xff, 0xff, 0xff, 0x00, 0xef],
                // [0x7e, 0x04, 0x01, 0x40, 0xff, 0xff, 0xff, 0x00, 0xef],
                // [0x7e, 0x07, 0x05, 0x03, 0xb1, 0x00, 0x33, 0x00, 0xef],
                // [0x7e, 0x05, 0x03, 0x80, 0x03, 0xff, 0xff, 0x00, 0xef]
            // ];
            $scope.title = '面膜导入';
            $scope.typeSrc = 'img/icons/daomo.svg';
            typeTime = $rootScope.Yzb_time;
    }

        SPAService.setYZBCurrentData($scope.title, SPAService.upKeepData.HYBsec, $scope.userMes.id, deviceName, mode, SPAService.upKeepData.maintain_sta);

    };



    //日他，写的他妈的只能在此基础上改了 写的比较垃圾
    var ble_name = JSON.parse(localStorage.getItem(BthSevice.address)).name;

    var kangzhou,quban,runfu,daomo,arr_data;

    var upKeepModeData = FetchDataService.getUpKeepModeData(); //焕颜宝理疗数据
    $scope.deviceLED = function(){
        // $http.get($myconfig.api.base_host + '/device/list_device_b')
        // .then(function(res){
            var minute = (parseInt(SPAService.upKeepData.typeTime/60).toString(16));
            if(minute.length == 1){
                minute = '0' + minute;
            }
            // for(var i = 0;i<res.data.data.length;i++){
            //     if(res.data.data[i].name == '焕颜宝'){
                    for(var j = 0;j<upKeepModeData.mode.length;j++){
                        // alert(upKeepModeData.mode[j].colormode);
                        var mode;
                        if(upKeepModeData.mode[j].colormode == 0){
                            mode = ['0x7e', '0x05', '0x03', '0x9d', '0x03', '0xff', '0xff', '0x00', '0xef'];
                        }


                        if(j == 0){
                            if(ble_name.indexOf('QMK-') > -1){ //搜索到的蓝牙名称必须包含QMK三个字母
                                if(upKeepModeData.mode[j].colormode == 0){
                                    kangzhou = [[
                                        '0x8a', //起始码
                                        '0x18',  //模式
                                        '0x' + (parseInt(upKeepModeData.mode[j].speed).toString(16)), //速度
                                        '0x' + (parseInt(upKeepModeData.mode[j].redlight).toString(16)), //亮度
                                        // '0x01', //倒计时
                                        '0x' + minute, //倒计时 分钟
                                        '0x00', //倒计时 秒
                                        '0x00', //红光
                                        '0x00',  //绿光
                                        '0x00' //蓝光
                                        // '0xaf' //结束码
                                    ]];

                                }else{
                                    kangzhou = [[
                                        '0x8a', //起始码
                                        '0x00',  //模式
                                        '0x00', //速度
                                        '0x' + (parseInt(upKeepModeData.mode[j].redlight).toString(16)), //亮度
                                        // '0x01', //倒计时
                                        '0x' + minute, //倒计时 分钟
                                        '0x00', //倒计时 秒
                                        '0x' + (parseInt(upKeepModeData.mode[j].redscale).toString(16)), //红光
                                        '0xe6',  //绿光
                                        '0x' + (parseInt(upKeepModeData.mode[j].bluescale).toString(16)) //蓝光
                                        // '0xaf' //结束码
                                    ]];
                                }
                            }else {
                                kangzhou = [
                                    // [0x7e, 0x04, 0x04, '0x01', 0xff, 0xff, 0xff, '0x00', '0xef'],//开关
                                    ['0x7e', '0x04', '0x01', '0x' + parseInt(upKeepModeData.mode[j].redlight).toString(16), '0xff', '0xff', '0xff', '0x00', '0xef'],//亮度
                                    ['0x7e', '0x04', '0x02', '0x' + parseInt(upKeepModeData.mode[j].speed).toString(16), '0xff', '0xff', '0xff', '0x00', '0xef'], // 设置速度
                                    // ['0x7e', '0x07', '0x05', '0x' + parseInt(upKeepModeData.mode[j].redscale).toString(16), '0xe6', '0x' + parseInt(upKeepModeData.mode[j].bluescale,16), 0x4d, '0x00', '0xef'] // 设置颜色强度
                                    ['0x7e', '0x07', '0x05', '0x03', '0x' + parseInt(upKeepModeData.mode[j].redscale).toString(16), '0x' + parseInt(upKeepModeData.mode[j].redscale).toString(16), '0x' + parseInt(upKeepModeData.mode[j].bluescale,16), '0x00', '0xef']
                                ];
                                if(upKeepModeData.mode[j].colormode == 0){
                                    // alert(kangzhou);
                                    kangzhou.push(mode);
                                }
                            }

                        }else if(j == 1){
                            if(ble_name.indexOf('QMK-') > -1){ //搜索到的蓝牙名称必须包含QMK三个字母
                                if(upKeepModeData.mode[j].colormode == 0){
                                    quban = [[
                                        '0x8a', //起始码
                                        '0x18',  //模式
                                        '0x' + (parseInt(upKeepModeData.mode[j].speed).toString(16)), //速度
                                        '0x' + (parseInt(upKeepModeData.mode[j].redlight).toString(16)), //亮度
                                        // '0x01', //倒计时
                                        '0x' + minute, //倒计时 分钟
                                        '0x00', //倒计时 秒
                                        '0x00', //红光
                                        '0x00',  //绿光
                                        '0x00' //蓝光
                                        // '0xaf' //结束码
                                    ]];

                                }else{
                                    quban = [[
                                        '0x8a', //起始码
                                        '0x00',  //模式
                                        '0x00', //速度
                                        '0x' + (parseInt(upKeepModeData.mode[j].redlight).toString(16)), //亮度
                                        // '0x01', //倒计时
                                        '0x' + minute, //倒计时 分钟
                                        '0x00', //倒计时 秒
                                        '0x' + (parseInt(upKeepModeData.mode[j].redscale).toString(16)), //红光
                                        '0xe6',  //绿光
                                        '0x' + (parseInt(upKeepModeData.mode[j].bluescale).toString(16)) //蓝光
                                        // '0xaf' //结束码
                                    ]];
                                }
                            }else {
                                quban = [
                                    // ['0x7e', '0x04', '0x04', '0x01', '0xff', '0xff', '0xff', '0x00', '0xef'],//开关
                                    ['0x7e', '0x04', '0x01', '0x' + parseInt(upKeepModeData.mode[j].redlight).toString(16), '0xff', '0xff', '0xff', '0x00', '0xef'],//亮度
                                    ['0x7e', '0x04', '0x02', '0x' + parseInt(upKeepModeData.mode[j].speed).toString(16), '0xff', '0xff', '0xff', '0x00', '0xef'], // 设置速度
                                    // ['0x7e', '0x07', '0x05', '0x' + parseInt(upKeepModeData.mode[j].redscale).toString(16), '0xe6', '0x' + parseInt(upKeepModeData.mode[j].bluescale,16), 0x4d, '0x00', '0xef'] // 设置颜色强度
                                    // ['0x7e', '0x05', '0x03', '0x' + parseInt(upKeepModeData.mode[j].colormode,16), '0x03', '0xff', '0xff', '0x00', '0xef']  // 设置模式
                                    ['0x7e', '0x07', '0x05', '0x03', '0x' + parseInt(upKeepModeData.mode[j].redscale).toString(16), '0x' + parseInt(upKeepModeData.mode[j].redscale).toString(16), '0x' + parseInt(upKeepModeData.mode[j].bluescale,16), '0x00', '0xef']
                                ];
                                if(upKeepModeData.mode[j].colormode == 0){
                                    // alert(quban);
                                    quban.push(mode);
                                }
                            }


                        }else if(j == 2){

                            if(ble_name.indexOf('QMK-') > -1){ //搜索到的蓝牙名称必须包含QMK三个字母
                                if(upKeepModeData.mode[j].colormode == 0){
                                    runfu = [[
                                        '0x8a', //起始码
                                        '0x18',  //模式
                                        '0x' + (parseInt(upKeepModeData.mode[j].speed).toString(16)), //速度
                                        '0x' + (parseInt(upKeepModeData.mode[j].redlight).toString(16)), //亮度
                                        // '0x01', //倒计时
                                        '0x' + minute, //倒计时 分钟
                                        '0x00', //倒计时 秒
                                        '0x00', //红光
                                        '0x00',  //绿光
                                        '0x00' //蓝光
                                        // '0xaf' //结束码
                                    ]];

                                }else{
                                    runfu = [[
                                        '0x8a', //起始码
                                        '0x00',  //模式
                                        '0x00', //速度
                                        '0x' + (parseInt(upKeepModeData.mode[j].redlight).toString(16)), //亮度
                                        // '0x01', //倒计时
                                        '0x' + minute, //倒计时 分钟
                                        '0x00', //倒计时 秒
                                        '0x' + (parseInt(upKeepModeData.mode[j].redscale).toString(16)), //红光
                                        '0xe6',  //绿光
                                        '0x' + (parseInt(upKeepModeData.mode[j].bluescale).toString(16)) //蓝光
                                        // '0xaf' //结束码
                                    ]];
                                }
                            }else {
                                runfu = [
                                    // ['0x7e', '0x04', '0x04', '0x01', '0xff', '0xff', '0xff', '0x00', '0xef'],//开关
                                    ['0x7e', '0x04', '0x01', '0x' + parseInt(upKeepModeData.mode[j].redlight).toString(16), '0xff', '0xff', '0xff', '0x00', '0xef'],//亮度
                                    ['0x7e', '0x04', '0x02', '0x' + parseInt(upKeepModeData.mode[j].speed).toString(16), '0xff', '0xff', '0xff', '0x00', '0xef'], // 设置速度
                                    // ['0x7e', '0x07', '0x05', '0x' + parseInt(upKeepModeData.mode[j].redscale).toString(16), '0xe6', '0x' + parseInt(upKeepModeData.mode[j].bluescale,16), 0x4d, '0x00', '0xef'], // 设置颜色强度
                                    // ['0x7e', '0x05', '0x03', '0x' + parseInt(upKeepModeData.mode[j].colormode,16), '0x03', '0xff', '0xff', '0x00', '0xef']  // 设置模式
                                    ['0x7e', '0x07', '0x05', '0x03', '0x' + parseInt(upKeepModeData.mode[j].redscale).toString(16), '0x' + parseInt(upKeepModeData.mode[j].redscale).toString(16), '0x' + parseInt(upKeepModeData.mode[j].bluescale,16), '0x00', '0xef']
                                ];
                                if(upKeepModeData.mode[j].colormode == 0){
                                    // alert(runfu);
                                    runfu.push(mode);
                                }
                            }



                        }else if(j == 3){

                            if(ble_name.indexOf('QMK-') > -1){ //搜索到的蓝牙名称必须包含QMK三个字母
                                if(upKeepModeData.mode[j].colormode == 0){
                                    daomo = [[
                                        '0x8a', //起始码
                                        '0x18',  //模式
                                        '0x' + (parseInt(upKeepModeData.mode[j].speed).toString(16)), //速度
                                        '0x' + (parseInt(upKeepModeData.mode[j].redlight).toString(16)), //亮度
                                        // '0x01', //倒计时
                                        '0x' + minute, //倒计时 分钟
                                        '0x00', //倒计时 秒
                                        '0x00', //红光
                                        '0x00',  //绿光
                                        '0x00' //蓝光
                                        // '0xaf' //结束码
                                    ]];

                                }else{
                                    daomo = [[
                                        '0x8a', //起始码
                                        '0x00',  //模式
                                        '0x00', //速度
                                        '0x' + (parseInt(upKeepModeData.mode[j].redlight).toString(16)), //亮度
                                        // '0x01', //倒计时
                                        '0x' + minute, //倒计时 分钟
                                        '0x00', //倒计时 秒
                                        '0x' + (parseInt(upKeepModeData.mode[j].redscale).toString(16)), //红光
                                        '0xe6',  //绿光
                                        '0x' + (parseInt(upKeepModeData.mode[j].bluescale).toString(16)) //蓝光
                                        // '0xaf' //结束码
                                    ]];
                                }
                            }else {
                                daomo = [
                                    // ['0x7e', '0x04', '0x04', '0x01', '0xff', '0xff', '0xff', '0x00', '0xef'],//开关
                                    ['0x7e', '0x04', '0x01', '0x' + parseInt(upKeepModeData.mode[j].redlight).toString(16), '0xff', '0xff', '0xff', '0x00', '0xef'],//亮度
                                    ['0x7e', '0x04', '0x02', '0x' + parseInt(upKeepModeData.mode[j].speed).toString(16), '0xff', '0xff', '0xff', '0x00', '0xef'], // 设置速度
                                    // ['0x7e', '0x07', '0x05', '0x' + parseInt(upKeepModeData.mode[j].redscale).toString(16), '0xe6', '0x' + parseInt(upKeepModeData.mode[j].bluescale,16), 0x4d, '0x00', '0xef'], // 设置颜色强度
                                    // ['0x7e', '0x05', '0x03', '0x' + parseInt(upKeepModeData.mode[j].colormode,16), '0x03', '0xff', '0xff', '0x00', '0xef']  // 设置模式
                                    ['0x7e', '0x07', '0x05', '0x03', '0x' + parseInt(upKeepModeData.mode[j].redscale).toString(16), '0x' + parseInt(upKeepModeData.mode[j].redscale).toString(16), '0x' + parseInt(upKeepModeData.mode[j].bluescale,16), '0x00', '0xef']
                                ];
                                if(upKeepModeData.mode[j].colormode == 0){
                                    // alert(daomo);
                                    daomo.push(mode);
                                }
                            }


                        }
                    }
                // }
            // }
            doIt();
        // });
    };
    $scope.deviceLED();


    /*var animator = $animateCss('.zhuan', {
        from: { background:'red' },
        to: { background:'blue' }
    });*/
    // animator.start();


    // var data = [0x7e, 0x05, 0x03, 0x80, 0x03, 0xff, 0xff, 0x00, 0xef]; // 设置RGB模式
    // BthSevice.write(valuesArr);
    // var data = [0x7e, 0x07, 0x05, 0x03, 0xe6, 0x00, 0x4d, 0x00, 0xef]; // 设置色盘
    // BthSevice.write(data);

    $scope.indicatorOption = {
        radius : 80,
        percentage :true,
        barColor : "#009CFF",
        barBgColor: "#CCEBFF",
        roundCorner: true,
        barWidth: 7,
        displayNumber: false,
        // frameTime: 1500,
        initValue : 0
    };

    var backcount = 0;
    /*if(SPAService.upKeepData.backcount){
        backcount = SPAService.upKeepData.backcount;
    }*/
    if (SPAService.upKeepData.backtime) {
        //当前时间减去返回时间是从退出到回到保养页面执行了多少秒钟
        backcount = Math.ceil((new Date().getTime() - SPAService.upKeepData.backtime) / 1000);
    }
    if (!SPAService.upKeepData.ts) {
        $scope.ts = SPAService.upKeepData.ts = SPAService.upKeepData.typeTime; //80秒
        SPAService.upKeepData.HYBsec = 0; //计算保养时间
    } else {

        $scope.ts = SPAService.upKeepData.ts -= backcount; //倒计时
    }


    var every = 100 / SPAService.upKeepData.typeTime;
    if (!SPAService.upKeepData.rotateCount) {
        $scope.rotateCount = SPAService.upKeepData.rotateCount = 45; //默认圆点从45°位置，即钟表12点钟
    } else {
        $scope.rotateCount = SPAService.upKeepData.rotateCount += backcount * 6; //加上离开的时间的角度
    }
    if (!SPAService.upKeepData.progress) {
        SPAService.upKeepData.progress = 0;
    } else {
        SPAService.upKeepData.progress += (every * backcount);
        // radialIndicatorInstance['indicator2'].animate(SPAService.upKeepData.progress); //恢复现在的进度
        // $timeout(function () {

        $scope.Count = $interval(down, 1000);
        // }, 1000);
    }


    // $scope.ts = $rootScope.Yzb_time; //80秒
    // var every = 100/$scope.ts;
    // var progress = 0; // 进度

    function down() {
        if(SPAService.upKeepData.ts < 1){
            $interval.cancel($scope.Count);
            $scope.resetTime(); // 重置
            BthSevice.closeLED(); // 完成后关闭led
            $rootScope.start = false; //停止运行
            SPAService.upKeepData.maintain_sta = 1;
            SPAService.setYZBCurrentData($scope.title, SPAService.upKeepData.HYBsec, $scope.userMes.id, deviceName, mode, SPAService.upKeepData.maintain_sta);
            SPAService.backgroundRunningYZB(true, new Date(), function() { //去记录当前的保养数据
                $rootScope.start = false; //停止运行
                $state.go('app.UpKeepingEnd', {
                    type: $scope.title
                });
            });
            /*$http.post($myconfig.api.base_host + '/users/maintain' ,{
                "user_id":$scope.userMes.id,
                "dev_name":deviceName,
                "mode":mode,
                "duration":$scope.HYBsec,
                "state":maintain_sta,
                "createtime":ThisTime
            }).then(function(res){
                // console.log(res.data.data);
                $scope.HYBsec = 0;
                $http.get($myconfig.api.base_host + '/physicallogs/finsh?user_id=' + $scope.userMes.id + '&mode=' + mode + '&dev_name=' + deviceName)
                .then(function(res){
                    // console.log(res.data.data);
                    res.data.data.duration = ((res.data.data.duration) / 60).toFixed(0);
                    res.data.data.totle_duration = ((res.data.data.totle_duration) / 60).toFixed(0);
                    $rootScope.finsh = res.data.data;
                });
            });*/

            return;
        }
        /*$scope.HYBsec++;
        progress += every; //每次执行进度条动多少
        radialIndicatorInstance['indicator1'].animate(progress);
        $scope.ts = $scope.ts - 1;*/
        SPAService.upKeepData.rotateCount += 6;
        $scope.rotateCount = SPAService.upKeepData.rotateCount;
        $scope.ngrotate = {
            '-webkit-transform': 'rotate(' + SPAService.upKeepData.rotateCount + 'deg)'
        }

        SPAService.upKeepData.HYBsec++;
        SPAService.upKeepData.progress += every; //每次执行进度条动多少
        radialIndicatorInstance['indicator1'].animate(SPAService.upKeepData.progress);
        $scope.ts = SPAService.upKeepData.ts = SPAService.upKeepData.ts - 1;
    }

    $scope.resetTime = function () {
        $scope.ts = SPAService.upKeepData.ts = SPAService.upKeepData.typeTime;
        SPAService.upKeepData.progress = 0;
        radialIndicatorInstance['indicator1'].animate(0); //重置为原点
        $("#zhuan1").removeClass('tf');
        if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
        }
    }


    var myPopup;
    // $("#zhuan1").css("animation-play-state", "paused");
    $scope.cancelTimer = function() {
        $scope.msg = '您确定要结束本次保养吗？';
        myPopup = $ionicPopup.show({
            templateUrl: 'templates/bitongbao/module/tishi.html',
            scope: $scope
        });
        $scope.myclose = function() {
            myPopup.close();
        };
        $scope.ok = function() {
            localStorage.removeItem('lastSPAEnd');
            myPopup.close();
            $rootScope.start = false;
            $interval.cancel($scope.Count);
            $scope.resetTime();
            $scope.state = '开始';
            BthSevice.closeLED(); // 完成后关闭led
            $scope.changePage = true;
            SPAService.upKeepData.maintain_sta = '0';
            $http.post($myconfig.api.base_host + '/users/maintain' ,{
                "user_id":$scope.userMes.id,
                "dev_name":deviceName,
                "mode":mode,
                "duration": SPAService.upKeepData.HYBsec,
                "state": SPAService.upKeepData.maintain_sta,
                "createtime": SPAService.upKeepData.ThisTime
            }).then(function(res){
                // console.log(res.data.data);
                // $scope.HYBsec = 0;
                SPAService.upKeepData.HYBsec = 0;
                $rootScope.start = false;
                SPAService.upKeepData = { stateText: '开始' };
                $http.get($myconfig.api.base_host + '/users/user_info?mobile=' + $rootScope._RootUser.mobile)
                    .then(function(res) {
                        if (res.data.success) {
                            localStorage.setItem('user', JSON.stringify(res.data.data));
                        }
                    });
            });

            //取消定时器
            // cordova.plugins.notification.local.cancel(1001, function () {
            //     // Notification was cancelled
            // });

            if (device.platform == "Android") {
              cordova.plugins.notification.local.cancel(1001, function () {
                  console.log('本地通知已取消');
              });
            }else { //ios直接清楚本地通知的所有对象，清除所有，应该没有其他的了吧
              window.plugins.jPushPlugin.clearAllLocalNotifications();
            }

            $state.go('app.YanZhiBao');
        };

    };

    // $scope.state = '开始';
    if (SPAService.upKeepData.stateText) {
        $scope.state = SPAService.upKeepData.stateText;
    } else {
        $scope.state = SPAService.upKeepData.stateText = '开始';
    }

    $scope.started = function() {
        if($scope.state == '开始'){
            $rootScope.start = true; //启动状态
            $scope.state = SPAService.upKeepData.stateText = '暂停';

            localStorage.setItem('lastSPAEnd', JSON.stringify({
                status: false,
                user_id: $scope.userMes.id,
                dev_name: deviceName,
                mode: mode,
                duration: SPAService.upKeepData.HYBsec,
                state: SPAService.upKeepData.maintain_sta,
                createtime: SPAService.upKeepData.ThisTime,
                type: 'face',
                typeTime: $scope.typeTime,
                spa_type: SPAService.upKeepData.type,
                stateText: SPAService.upKeepData.stateText
            }));

            // SPAService.upKeepData.radialIndicatorInstance = radialIndicatorInstance['indicator1'];

            BthSevice.write($scope.valuesArr); // 开始之后亮起设置led
            $interval.cancel($scope.Count);
            $scope.resetTime();
            // $("#zhuan1").addClass('tf');
            $scope.Count = $interval(down, 1000);

            setSchedule(SPAService.upKeepData.typeTime * 1000); //开启本地通知,规定的时间完成后本地通知完成

            // $("#zhuan1").css("animation-play-state", "running");
        }else if($scope.state == '暂停'){

            localStorage.setItem('lastSPAEnd', JSON.stringify({status: true}));

            BthSevice.closeLED(); // 完成后关闭led
            $rootScope.start = false; //暂停状态
            // $scope.state = '继续';
            $scope.state = SPAService.upKeepData.stateText = '继续';
            $interval.cancel($scope.Count);

            // cordova.plugins.notification.local.cancel(1001, function () { //先取消，等继续后再创建定时器
            //     console.log('本地通知已取消');
            // });
            if (device.platform == "Android") {
              cordova.plugins.notification.local.cancel(1001, function () {
                  console.log('本地通知已取消');
              });
            }else {
              window.plugins.jPushPlugin.clearAllLocalNotifications();
            }
            // $("#zhuan1").addClass('tf');
            // Count = $interval(down, 1000);
            // $("#zhuan1").css("animation-play-state", "paused");
        }else{
            $rootScope.start = true; //暂停状态
            $scope.state = SPAService.upKeepData.stateText = '暂停';

            localStorage.setItem('lastSPAEnd', JSON.stringify({
                status: false,
                user_id: $scope.userMes.id,
                dev_name: deviceName,
                mode: mode,
                duration: SPAService.upKeepData.HYBsec,
                state: SPAService.upKeepData.maintain_sta,
                createtime: SPAService.upKeepData.ThisTime,
                type: 'face',
                typeTime: $scope.typeTime,
                spa_type: SPAService.upKeepData.type,
                stateText: SPAService.upKeepData.stateText
            }));

            var time = SPAService.upKeepData.ts; //如果继续计算剩余的时间
            console.log('剩余时间：' + time);
            var minutes = Math.floor(time/60); //剩余分钟
            minutes = (parseInt(minutes).toString(16));
            if(minutes.length == 1){
                minutes = '0' + minutes;
            }

            var seconds = (time-Math.floor(time/60)*60); //剩余秒钟
            seconds = (parseInt(seconds).toString(16));
            if(seconds.length == 1){
                seconds = '0' + seconds;
            }
            $scope.valuesArr[0].splice(
                4,
                2,
                '0x' + minutes,
                '0x' + seconds)

            BthSevice.write($scope.valuesArr); // 开始之后亮起设置led
            $scope.Count = $interval(down, 1000);

            setSchedule(time); //开启本地通知
            // $("#zhuan1").css("animation-play-state", "running");
        }
    };

    function setSchedule(time) {
        if(device.platform == 'Android'){ //安卓的走这个插件的本地通知
          cordova.plugins.notification.local.schedule({
              id: 1001,
              title: '健康保养',
              text: '您正在进行的' + $rootScope.mode + '保养已完成。',
              at: new Date().getTime() + time,
              // badge: 1,
              autoClear: true, //默认值
              sound: 'res://platform_default', //默认值
              // sound: 'file://sounds/message.mp3',
              icon: 'res://drawable-xxxhdpi/icon.png', //默认值
              ongoing: false //默认值
          });
        }else {
          window.plugins.jPushPlugin.addLocalNotificationForIOS(
            time / 1000,
            '您正在进行的' + $rootScope.mode + '保养已完成。',
            1,
            "1000", {"key":"value"}
          );
        }

    }

    $scope.$on('$destroy', function() {
        $interval.cancel($scope.Count);
    });

    SPAService.upKeepData.thePage = true; //标记在保养页面 在保养界面就不需要定时器发送保养数据到服务器
    $scope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
        // console.log(toState.name + '~~~~~~~~~~~~~~~~~~');
        SPAService.upKeepData.thePage = false; //标记为离开
        if (toState.name == 'app.YanZhiBao' && !$scope.changePage) {

            if (!$rootScope.start) { //停止状态直接清除数据
                $interval.cancel($scope.Count);
                $scope.resetTime();
                // $("#zhuan2").css("animation-play-state", "paused");
                BthSevice.closeLED(); // 完成后关闭led
                $scope.changePage = true;
                SPAService.upKeepData = { stateText: '开始' };
                // $state.go('app.BiGuangBao');
            } else {
                SPAService.upKeepData.backtime = new Date().getTime(); //记录返回到首页的时间
                SPAService.upKeepData.maintain_sta = 1; //从这里返回默认为可以保养完成

                /*cordova.plugins.notification.local.schedule({
                    id: 1001,
                    title: '健康保养',
                    text: '您正在进行的' + $rootScope.mode + '保养已完成。',
                    at: new Date().getTime() + 5000,
                    // badge: 1,
                    autoClear: true, //默认值
                    sound: 'res://platform_default', //默认值
                    icon: 'res://drawable-xxxhdpi/icon.png', //默认值
                    ongoing: false //默认值
                });*/
            }

            return;
            event.preventDefault();
            $scope.msg = '您确定要结束本次保养吗？';
            myPopup = $ionicPopup.show({
                templateUrl: 'templates/bitongbao/module/tishi.html',
                scope: $scope
            });
            $scope.myclose = function() {
                myPopup.close();
            };
            $scope.ok = function() {
                myPopup.close();
                $rootScope.start = false;
                maintain_sta = '0';
                $http.post($myconfig.api.base_host + '/users/maintain' ,{
                    "user_id":$scope.userMes.id,
                    "dev_name":deviceName,
                    "mode":mode,
                    "duration":$scope.HYBsec,
                    "state":maintain_sta,
                    "createtime":ThisTime
                }).then(function(res){
                    // console.log(res.data.data);
                    $scope.HYBsec = 0;
                });
                $interval.cancel($scope.Count);
                $scope.Count = null;
                $scope.resetTime();
                $("#zhuan1").css("animation-play-state", "paused");
                BthSevice.closeLED(); // 完成后关闭led
                $scope.changePage = true;
                $state.go('app.YanZhiBao');
            };
        }else if(myPopup){
            myPopup.close();
        }
    });
    $scope.$on('$destroy',function(){
        $interval.cancel($scope.Count);
    });

    $scope.goBack = function () {
        $state.go('app.YanZhiBao');
    };
    $scope.$on('$ionicView.enter', function(){

        $ionicConfig.views.swipeBackEnabled(false);

    });

    //退出的时候取消当前页定时器
    $scope.$on('stopInterval', function (event) {
        // $interval.cancel($scope.Count);
    });

    //程序从后台恢复时会收到此事件通知 恢复从后台到当前时间的动态效果
    $scope.$on('isResume', function (event, data) {
        if(data){
            console.log('校准倒计时效果');
            // $interval.cancel($scope.Count);
            // $scope.Count = null;
            if (SPAService.upKeepData.backtime) {
                backcount = Math.ceil((new Date().getTime() - SPAService.upKeepData.backtime) / 1000);
                console.log('程序在后台运行' + backcount + '秒 ' + SPAService.upKeepData.backtime);
                console.log('程序在后台运行' + backcount/60 + '分钟 ');
                // console.log('')
            }
            console.log(SPAService.upKeepData.backts);
            $scope.ts = SPAService.upKeepData.ts = SPAService.upKeepData.backts -= backcount; //倒计时

            // var every = 100 / SPAService.upKeepData.typeTime;

            $scope.rotateCount = SPAService.upKeepData.rotateCount = SPAService.upKeepData.backrotateCount += backcount * 6; //加上离开的时间的角度

            SPAService.upKeepData.progress = SPAService.upKeepData.backprogress += (every * backcount);
                // radialIndicatorInstance['indicator2'].animate(SPAService.upKeepData.progress); //恢复现在的进度
                /*$timeout(function () {

                $scope.Count = $interval(down, 1000);
                }, 1000);*/
            /*$timeout(function () {
                $state.reload();
            }, 1000);*/
            // $scope.doRefresh();
        }
    });
});
